from typing import Any
import httpx
import logging
import os
import sys

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
sys.path.append(os.path.dirname(os.path.dirname(__file__)))



import sys
from pathlib import Path
# 在 weather_baidu_webapi.py 文件开头添加
project_root = Path(__file__).parent.parent.parent.parent  # 根据实际情况调整
sys.path.append(str(project_root))

## 配置文件读取helper工具
from shared.utils.helper import get_config

## 开始读取配置文件并保存到常量 Constants
try:
    # 配置文件路径
    weather_project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) # api-> src -> weather-mcp-server
    config_dir = os.path.join(weather_project_root, "config")
    config = get_config("config.yaml",config_dir)
    if not config:
        raise ValueError("Failed to load config.yaml")
    API_BASE_URL = config["baidu"]["weather"]["api_base_url"]
    
    secrets = get_config("env/secrets.yaml", project_root.parent)
    if not secrets:
        raise ValueError("Failed to load secrets.yaml")
    API_KEY = secrets["baidu"]["weather"]["api_key"]
except Exception as e:
    logger.error(f"Failed to load configuration: {str(e)}")
    raise

USER_AGENT = "weather-app/1.0"

async def make_request(url: str) -> dict[str, Any] | None:
    """Make a request to the BAIDU API with proper error handling."""
    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "application/geo+json"
    }
    # logger.info(f"准备请求百度天气API, URL: {url}")
    logger.info(f"准备请求百度天气API")
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(url, headers=headers, timeout=30.0)
            response.raise_for_status()
            logger.info(f"百度天气API请求成功, 状态码: {response.status_code}")
            return response.json()
        except Exception as e:
            logger.error(f"百度天气API请求失败: {str(e)}")
            return None

def format_weather_data(response: dict) -> str:
    """Format an weather data into a readable string."""
    try:
        result = response.get("result", {})
        now_elem = result.get("now", {})
        return f"""
        当前天气: {now_elem.get('text', '未知')}
        温度: {now_elem.get('temp', '未知')}°C
        风力等级: {now_elem.get('wind_class', '未知')}
        风向: {now_elem.get('wind_dir', '未知')}
        """
    except Exception as e:
        return f"格式化天气数据出错: {str(e)}\n原始响应: {response}"

async def get_weather(district_id: str, data_type: str, debug: bool = False) -> str:
    """Get weather forecast for a location.

    Args:
        disctric_id: code for the disctric
    """
    logger.info(f"开始获取天气数据, 地区ID: {district_id}, 数据类型: {data_type}")
    # https://api.map.baidu.com/weather/v1/?district_id=110100&data_type=now

    # First get the weather endpoint
    weather_api_url = f"{API_BASE_URL}?district_id={district_id}&data_type={data_type}&ak={API_KEY}"
    weather_data = await make_request(weather_api_url)

    if not weather_data:
        logger.error(f"获取天气数据失败, 地区ID: {district_id}")
        return f"无法获取该地区天气数据。API响应: {weather_data}"

    # Format the response into a readable forecast
    response = weather_data
    
    # 调试api响应结果
    if debug:
        logger.debug(f"API原始响应: {response}")
        print(response)

    logger.info(f"成功获取并格式化天气数据, 地区ID: {district_id}")
    logger.info(f"response： {response}")
    
    return format_weather_data(response)


if __name__ == "__main__":

    # 解析命令行参数
    import argparse
    
    ## 当没有命令行参数时，打印帮助信息
    if len(sys.argv) == 1:
        print("""
        请输入以下参数：
        --district_id: 查询城市Code
        --data_type: 查询数据类型
        """)
        sys.exit(1)

    parser = argparse.ArgumentParser(description='查询天气')
    parser.add_argument('--district_id', help='查询城市Code')
    parser.add_argument('--data_type', help='查询数据类型')
    args = parser.parse_args()

    if args:
        if args.district_id and args.data_type:
            import asyncio
            asyncio.run(get_weather(args.district_id, args.data_type))
    else:
        parser.print_help()

